package pt.mauromad.guias.dao;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import pt.mauromad.guias.dao.security.RoleDao;

@Entity
@Table(name = "account")
public class AccountDao {
	private Long id;
	private DomainDao domain;
	private boolean enabled = false;
	private CompanyDao company;
	private List<CompanyDao> companies = new LinkedList<>();

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "id")
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.DETACH, optional = false)
	@JoinColumn(name = "domain_id", insertable = true, updatable = false, nullable = false)
	public DomainDao getDomain() {
		return domain;
	}

	public void setDomain(DomainDao domain) {
		this.domain = domain;
	}

	@Transient
	public List<UserDao> getUsers() {
		return getDomain().getUsers();
	}

	@OneToMany(mappedBy = "account", fetch = FetchType.EAGER, cascade = CascadeType.DETACH)
	@Fetch(value = FetchMode.SUBSELECT)
	public List<CompanyDao> getCompanies() {
		return companies;
	}

	public void setCompanies(List<CompanyDao> companies) {
		this.companies = companies;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(boolean enabled) {
		this.enabled = enabled;
	}

	@OneToOne(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
	@JoinColumn(name = "main_company_id")
	public CompanyDao getCompany() {
		return company;
	}

	public void setCompany(CompanyDao company) {
		this.company = company;
	}

	@Transient
	public List<UserDao> getAccountManagers() {
		List<UserDao> managers = new ArrayList<>();

		for (UserDao dao : getDomain().getUsers()) {
			if (dao.hasRole(RoleDao.ROLE_ACCOUNT_MANAGER))
				managers.add(dao);
		}

		return managers;
	}

	@Transient
	public List<UserDao> getAccountUsers() {
		List<UserDao> managers = new ArrayList<>();

		for (UserDao dao : getDomain().getUsers()) {
			if (dao.hasRole(RoleDao.ROLE_ACCOUNT_USER))
				managers.add(dao);
		}

		return managers;
	}
}
